package serv

import (
	"log"
	"net"
	"netfly/comm"

	"github.com/satori/go.uuid"
	"github.com/tidwall/gjson"
)

var (
	_clientList map[string]net.Conn
)

func ClientListPush(c net.Conn) string {
	uid := uuid.NewV4().String()
	_clientList[uid] = c
	log.Println(uid, c.RemoteAddr())
	return uid
}

func ClientListGet(uid string) (c net.Conn) {
	v, ok := _clientList[uid]
	if ok {
		c = v
	}
	return
}

func ClientListRemove(uid string) {
	delete(_clientList, uid)
}

func HandleDataConn(c net.Conn) {
	//log.Println("DataConn", c.RemoteAddr().String())
	// data client uid
	//uid := ClientListPush(c)
	strMsg, _ := comm.WaitCtrlMsg(c, 0)
	strUid := gjson.Get(strMsg, "uid").String()

	cPort := ClientListGet(strUid)
	log.Println("Data Conn:", strUid, cPort.RemoteAddr().String(), c.RemoteAddr().String())
	comm.MakeTunnel(cPort, c)

	// tell client to clear
	// clear
	c.Close()
	cPort.Close()
	ClientListRemove(strUid)
}

func RunDataServer(strAddr string) {
	log.Println("Listen DataServer", strAddr)
	sListen, err := net.Listen("tcp", strAddr)
	if err != nil {
		log.Println("Listen", strAddr, "Error:", err.Error())
		return
	}
	defer sListen.Close()
	if _clientList == nil {
		_clientList = make(map[string]net.Conn)
	}
	for {
		cConn, err := sListen.Accept()
		if err != nil {
			continue
		}
		go HandleDataConn(cConn)
	}
}
